﻿using System;
using System.Linq;

using Infrastructure.Diagnostics;
using TempEmployees.DAL;
using TempEmployees.BLL.Database;

namespace TempEmployees.BLL.EntitiesExtensions
{
    public static class EEmployee 
    {
        public static Employee CreateEmployee(string id, string firstName, string lastName, DateTime birthDate, string address, string phone,
                            string cellular, string email, int facultyId, int startSemesterId)
        {
            Employee employee = new Employee();
            employee.ID = id;
            employee.FirstName = firstName;
            employee.LastName = lastName;
            employee.BirthDate = birthDate;
            employee.Address = address;
            employee.Phone = phone;
            employee.CellPhone = cellular;
            employee.Email = email;
            employee.FacultyID = facultyId;
            employee.StartSemesterID = startSemesterId;
            return employee;
        }

        public static bool InsertEmployee(Employee employee)
        {
            if (IsEmployeeExists(employee.ID)) return true;  //employee already in the DB

            if (DbQuery.Insert(employee))
            {
                Logger.Debug("Inserted new employee, ID: {0}", employee.ID);
                return true;
            }
            else
            {
                Logger.Error("failed to insert new employee, ID: {0}", employee.ID);
                return false;
            }
        }

        public static bool UpdateEmployee(Employee employee)
        {
            if (!IsEmployeeExists(employee.ID)) throw new RecordNotInDbException("UpdateEmployee: employee not found in the DB"); 

            if (DbQuery.Update<Employee>(employee, GetEmployeeByID(employee.ID)))
            {
                Logger.Debug("updated employee, ID: {0}", employee.ID);
                return true;
            }
            else
            {
                Logger.Error("failed to update employee, ID: {0}", employee.ID);
                return false;
            }
        }

        public static Employee GetEmployeeByID(string id)
        {
            return DbQuery.GetSingleRow<Employee>("ID", id);
        }

        private static bool IsEmployeeExists(string ID)
        {
            return (DbQuery.GetSingleRow<Employee>("ID", ID) != null);
        }
    }
}
